 ///
 /// @file    observer.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2016-03-17 15:54:15
 ///
 
#include "observer.h"
#include <iostream>
#include <algorithm>
using std::cout;
using std::endl;


void Subject::attach(Observer * observer)
{
	cout << "Attach()" << endl;
	_observerList.push_back(observer);
}

void Subject::detach(Observer * observer)
{
	list<Observer*>::iterator iter;
	iter = std::find(_observerList.begin(), 
				     _observerList.end(),
					 observer);
	if(iter != _observerList.end())
	{
		_observerList.erase(iter);
	}
	cout << "Detach()" << endl;
}

void Subject::notify()
{
	list<Observer*>::iterator iter;
	for(iter = _observerList.begin();
		iter != _observerList.end();
		++iter)
	{
		(*iter)->update(this);
	}
	cout << "notify all observers" << endl;
}


void Subject::setState(State nState)
{
	_myState = nState;
}

State Subject::getState()
{
	return _myState;
}

Subject::~Subject()
{
	cout << "~Subject()" << endl;
	_observerList.clear();
}


void ConcreateSubject::setState(State nState)
{
	_myState = nState;
}

State ConcreateSubject::getState()
{
	return _myState;
}
//void ConcreateObserver::update(Message & msg);//推模式
void ConcreateObserver::update(Subject * subject)//拉模式
{
	if(subject != NULL)
	{
		_observerState = subject->getState();
	}
	cout << "the Subject's state is " << _observerState << endl;
}

